<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">服务管理</h1>
      <p class="page-description">查看和管理所有服务信息</p>
    </div>
    
    <!-- 筛选器 -->
    <a-card class="filter-card" :bordered="false">
      <div class="filter-container">
        <a-form :model="serviceStore.filters" @submit="handleSearch" class="filter-form" :label-col-style="{ width: '80px', flexShrink: 0 }">
          <!-- 第一行 -->
          <div class="filter-row">
            <a-form-item label="服务名称" class="filter-item">
              <a-input
                v-model="serviceStore.filters.name"
                placeholder="搜索服务名称"
                allow-clear
                style="width: 180px"
              />
            </a-form-item>
            
            <a-form-item label="服务类型" class="filter-item">
              <a-select
                v-model="serviceStore.filters.type_id"
                placeholder="选择服务类型"
                allow-clear
                style="width: 180px"
              >
                <a-option
                  v-for="type in serviceTypes"
                  :key="type.id"
                  :value="type.id"
                >
                  {{ type.name }}
                </a-option>
              </a-select>
            </a-form-item>
            
            <a-form-item class="button-group">
              <a-space :size="8">
                <a-button type="primary" html-type="submit" :loading="serviceStore.loading">
                  <template #icon>
                    <icon-search />
                  </template>
                  搜索
                </a-button>
                <a-button @click="handleReset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </div>
        </a-form>
        
        <div class="action-buttons">
          <a-space :size="12">
            <a-button type="primary" @click="handleAddService">
              <template #icon>
                <icon-plus />
              </template>
              添加服务
            </a-button>
            <a-button @click="handleExport">
              <template #icon>
                <icon-download />
              </template>
              导出数据
            </a-button>
          </a-space>
        </div>
      </div>
    </a-card>
    
    <!-- 服务列表 -->
    <a-card class="table-card" :bordered="false">
      <a-table
        :columns="columns"
        :data="serviceStore.services"
        :loading="serviceStore.loading"
        :pagination="paginationConfig"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #price="{ record }">
          ¥{{ record.price?.toLocaleString() || 0 }}
        </template>
        
        <template #actions="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleViewService(record)">
              <template #icon>
                <icon-eye />
              </template>
              查看
            </a-button>
            <a-button type="text" size="small" @click="handleEditService(record)">
              <template #icon>
                <icon-edit />
              </template>
              编辑
            </a-button>
            <a-button type="text" size="small" status="danger" @click="handleDeleteService(record)">
              <template #icon>
                <icon-delete />
              </template>
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
    
    <!-- 服务表单模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :width="600"
      :ok-text="modalMode === 'view' ? '关闭' : '确定'"
      :hide-cancel="modalMode === 'view'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="服务名称" field="name">
          <a-input 
            v-model="formData.name" 
            placeholder="请输入服务名称"
            :disabled="modalMode === 'view'"
          />
        </a-form-item>
        
        <a-form-item label="服务描述" field="description">
          <a-textarea
            v-model="formData.description"
            placeholder="请输入服务描述"
            :rows="3"
            :disabled="modalMode === 'view'"
          />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="价格" field="price">
              <a-input-number
                v-model="formData.price"
                placeholder="请输入价格"
                :min="0"
                :precision="2"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务状态" field="status">
              <a-switch 
                v-model="formData.status"
                :disabled="modalMode === 'view'"
              />
              <span class="ml-2">{{ formData.status ? '启用' : '禁用' }}</span>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="服务分类" field="category">
          <a-select
            v-model="formData.category"
            placeholder="请选择服务分类"
            :disabled="modalMode === 'view'"
            style="width: 100%"
          >
            <a-option value="room">客房服务</a-option>
            <a-option value="dining">餐饮服务</a-option>
            <a-option value="entertainment">娱乐服务</a-option>
            <a-option value="business">商务服务</a-option>
            <a-option value="other">其他服务</a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { useServiceStore } from '@/stores/service'
import { getServiceTypes } from '@/api/service'
import {
  IconPlus,
  IconEye,
  IconEdit,
  IconDelete,
  IconDownload,
  IconSearch,
  IconRefresh
} from '@arco-design/web-vue/es/icon'

// 使用 service store
const serviceStore = useServiceStore()

// 服务类型列表
const serviceTypes = ref([])

// 模态框状态
const modalVisible = ref(false)
const modalTitle = ref('')
const modalMode = ref('add') // add | edit | view
const currentServiceId = ref(null)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  name: '',
  description: '',
  price: 0,
  status: true,
  category: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入服务名称' }
  ],
  description: [
    { required: true, message: '请输入服务描述' }
  ],
  price: [
    { required: true, message: '请输入价格' },
    { type: 'number', min: 0, message: '价格必须大于等于0' }
  ],
  category: [
    { required: true, message: '请选择服务分类' }
  ]
}

// 表格列配置
const columns = [
  { title: '服务名称', dataIndex: 'name', width: 150 },
  { title: '描述', dataIndex: 'description', width: 200 },
  { title: '价格', slotName: 'price', width: 100 },
  { title: '服务类型', dataIndex: 'type_name', width: 120 },
  { title: '创建时间', dataIndex: 'created_at', width: 150 },
  { title: '操作', slotName: 'actions', width: 180, fixed: 'right' }
]

// 分页配置
const paginationConfig = computed(() => ({
  current: serviceStore.pagination.current,
  pageSize: serviceStore.pagination.size,
  total: serviceStore.pagination.total,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
}))

// 处理分页变化
const handlePageChange = (page) => {
  serviceStore.setPagination({ current: page })
  serviceStore.fetchServices()
}

// 处理页面大小变化
const handlePageSizeChange = (size) => {
  serviceStore.setPagination({ size, current: 1 })
  serviceStore.fetchServices()
}

// 获取服务分类文本
const getCategoryText = (category) => {
  const categories = {
    room: '客房服务',
    dining: '餐饮服务',
    entertainment: '娱乐服务',
    business: '商务服务',
    other: '其他服务'
  }
  return categories[category] || category
}

// 处理搜索
const handleSearch = () => {
  serviceStore.setPagination({ current: 1 })
  serviceStore.fetchServices()
}

// 处理重置
const handleReset = () => {
  serviceStore.resetFilters()
  serviceStore.fetchServices()
}

// 处理导出数据
const handleExport = () => {
  try {
    const exportData = serviceStore.services.map(service => ({
      '服务名称': service.name,
      '服务描述': service.description || '-',
      '价格(元)': service.price || 0,
      '服务类型': service.type_name || '-',
      '创建时间': service.created_at || '-'
    }))

    const headers = Object.keys(exportData[0])
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => headers.map(header => {
        const value = row[header]
        if (typeof value === 'string' && (value.includes(',') || value.includes('\n'))) {
          return `"${value.replace(/"/g, '""')}"`
        }
        return value
      }).join(','))
    ].join('\n')

    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `服务数据_${new Date().toLocaleDateString()}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    Message.success('导出成功！')
  } catch (error) {
    console.error('导出失败:', error)
    Message.error('导出失败，请重试')
  }
}

// 处理添加服务
const handleAddService = () => {
  modalMode.value = 'add'
  modalTitle.value = '添加服务'
  resetForm()
  modalVisible.value = true
}

// 处理查看服务
const handleViewService = (record) => {
  modalMode.value = 'view'
  modalTitle.value = '服务详情'
  fillForm(record)
  modalVisible.value = true
}

// 处理编辑服务
const handleEditService = (record) => {
  modalMode.value = 'edit'
  modalTitle.value = '编辑服务'
  currentServiceId.value = record.id
  fillForm(record)
  modalVisible.value = true
}

// 处理删除服务
const handleDeleteService = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除服务"${record.name}"吗？此操作无法撤销。`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      await serviceStore.deleteServiceData(record.id)
    }
  })
}

// 处理模态框确认
const handleModalOk = async () => {
  if (modalMode.value === 'view') {
    modalVisible.value = false
    return
  }
  
  const valid = await formRef.value.validate()
  if (!valid) return
  
  let success = false
  if (modalMode.value === 'add') {
    success = await serviceStore.createServiceData(formData)
  } else if (modalMode.value === 'edit') {
    success = await serviceStore.updateServiceData(currentServiceId.value, formData)
  }
  
  if (success) {
    modalVisible.value = false
  }
}

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
}

// 填充表单
const fillForm = (record) => {
  Object.assign(formData, {
    name: record.name || '',
    description: record.description || '',
    price: record.price || 0,
    status: record.status || true,
    category: record.category || ''
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    description: '',
    price: 0,
    status: true,
    category: ''
  })
  formRef.value?.resetFields()
}

// 获取服务类型列表
const fetchServiceTypes = async () => {
  try {
    const data = await getServiceTypes()
    // axios 响应拦截器已经返回了 data.data
    serviceTypes.value = data || []
    console.log('服务类型列表:', serviceTypes.value)
  } catch (error) {
    console.error('获取服务类型失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchServiceTypes()
  serviceStore.fetchServices()
})
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 16px;
}

.page-title {
  margin: 0;
}

.filter-card {
  margin-bottom: 12px;
  
  :deep(.arco-card-body) {
    padding: 12px 16px;
  }
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
  
  @media (max-width: 1024px) {
    flex-direction: column;
    gap: 8px;
  }
}

.filter-form {
  flex: 1;
  min-width: 0;
}

.filter-row {
  display: grid;
  grid-template-columns: 240px 240px auto;
  gap: 8px 12px;
  align-items: center;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  @media (max-width: 1200px) {
    grid-template-columns: 240px 240px;
  }
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 8px;
  }
}

.filter-item {
  display: flex;
  align-items: center;
  
  :deep(.arco-form-item) {
    margin-bottom: 0;
    width: 100%;
    display: flex;
    align-items: center;
  }
  
  :deep(.arco-form-item-label-col) {
    width: 70px;
    flex: 0 0 70px;
    padding-right: 6px;
  }
  
  :deep(.arco-form-item-label) {
    font-weight: 500;
    color: #1d2129;
    white-space: nowrap;
    text-align: right;
    width: 100%;
    font-size: 13px;
  }
  
  :deep(.arco-form-item-wrapper-col) {
    flex: 1;
    min-width: 0;
  }
  
  :deep(.arco-input-wrapper),
  :deep(.arco-select-view),
  :deep(.arco-picker) {
    width: 100%;
    max-width: 160px;
    min-width: 160px;
  }
}

.button-group {
  grid-column: 3;
  grid-row: 1;
  display: flex;
  justify-content: flex-end;
  
  :deep(.arco-form-item) {
    margin-bottom: 0;
  }
  
  @media (max-width: 1200px) {
    grid-column: 1 / -1;
    grid-row: auto;
    margin-top: 4px;
    justify-content: flex-end;
  }
  
  @media (max-width: 768px) {
    width: 100%;
    
    :deep(.arco-space) {
      width: 100%;
      display: flex;
      
      .arco-btn {
        flex: 1;
      }
    }
  }
}

.action-buttons {
  flex-shrink: 0;
  
  @media (max-width: 1024px) {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
  
  @media (max-width: 768px) {
    :deep(.arco-space) {
      width: 100%;
      display: flex;
      
      .arco-btn {
        flex: 1;
      }
    }
  }
}

.table-card {
  margin-bottom: 16px;
}

.ml-2 {
  margin-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .page-header > .arco-space {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
